package com.xinjie.www.servlet;

import com.xinjie.www.service.post.PostServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;

public class PostServlet extends HttpServlet {
    PostServiceImpl postService = new PostServiceImpl();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");
        if ("delete".equals(method)) {
            try {
                this.deletePost(req, resp);
            } catch (SQLException | ClassNotFoundException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

    private void deletePost(HttpServletRequest req, HttpServletResponse resp) throws IOException, SQLException, ClassNotFoundException {
        int id = Integer.parseInt(req.getParameter("id"));
        String tieba = req.getParameter("tieba");
        boolean b = postService.deletePost(id, tieba);
        if (b) {
            req.getSession().setAttribute("deletePostSuccess", "删除帖子成功");
            if ("user".equals(req.getParameter("identity"))) {
                resp.sendRedirect("/UserPage/LookOwnPost.jsp");
            } else {
                if ("report".equals(req.getParameter("from"))){
                    resp.sendRedirect("/ManagerPage/LookReport.jsp");
                }else {
                    resp.sendRedirect("/ManagerPage/ManagerFrame.jsp");
                }
            }
        } else {
            req.getSession().setAttribute("deletePostLose", "删除帖子失败");
            if ("user".equals(req.getParameter("identity"))) {
                resp.sendRedirect("/UserPage/LookOwnPost.jsp");
            } else {
                if ("report".equals(req.getParameter("from"))){
                    resp.sendRedirect("/ManagerPage/LookReport.jsp");
                }else {
                    resp.sendRedirect("/ManagerPage/ManagerFrame.jsp");
                }
            }
        }
    }
}
